package com.liuwei.learning.controller;

import com.liuwei.learning.model.AjaxResponse;
import com.liuwei.learning.jpa.testdb1.Article;
import com.liuwei.learning.model.ArticleVO;
import com.liuwei.learning.service.ArticleRestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.PUT;

@Slf4j
@RestController
@RequestMapping("/rest")
public class ArticleRestController {

    @Resource(name = "articleRestJPAServiceImpl")
    private ArticleRestService articleRestService;

    //添加文章
    @RequestMapping(value = "/article",method = RequestMethod.POST,produces = "application/json")
    public AjaxResponse saveArticle(@RequestBody ArticleVO article){
        log.info("articleRestService return :" + articleRestService.saveArticle(article));

        return AjaxResponse.success(article);
    }
    //删除一篇Article，使用DELETE方法，参数是id
    @RequestMapping(value = "/article/{id}", method = RequestMethod.DELETE, produces = "application/json")
    public AjaxResponse deleteArticle(@PathVariable Long id) {
        articleRestService.deleteArticle(id);
        return AjaxResponse.success(id);
    }

    //更新一篇Article，使用PUT方法，以id为主键进行更新
    @RequestMapping(value = "/article/{id}", method = PUT, produces = "application/json")
    public AjaxResponse updateArticle(@PathVariable Long id, @RequestBody ArticleVO article) {
        article.setId(id);
        articleRestService.updateArticle(article);
        return AjaxResponse.success(article);
    }

    //获取一篇Article，使用GET方法
    @RequestMapping(value = "/article/{id}", method = GET, produces = "application/json")
    public AjaxResponse getArticle(@PathVariable Long id) {

        //使用lombok提供的builder构建对象
        Article article1 = Article.builder()
                .id(1L)
                .author("zimug")
                .content("spring boot 2.深入浅出")
                .createTime(new Date())
                .title("t1").build();
        return AjaxResponse.success(article1);
    }

    @GetMapping( "/article")
    public @ResponseBody  AjaxResponse getAllArticle() {

        return AjaxResponse.success(articleRestService.getAll());
    }
}
